import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import { authApi } from '@/api'
import { 
  getToken, 
  setToken, 
  removeToken, 
  getUserInfo, 
  setUserInfo, 
  removeUserInfo,
  isLoggedIn as checkIsLoggedIn,
  clearAuth,
  type UserInfo 
} from '@/utils/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(getToken())
  const user = ref<UserInfo | null>(getUserInfo())
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!(token.value && user.value))
  const username = computed(() => user.value?.username || '')
  const nickname = computed(() => user.value?.nickname || '')
  const role = computed(() => user.value?.role || 0)
  
  // 登录方法
  const login = async (username: string, password: string) => {
    try {
      loading.value = true
      
      const response = await authApi.login({ username, password })

      if (response.status === 'success') {
        // 设置token和用户信息
        const { jwt_token, ...userInfo } = response.data
        
        token.value = jwt_token
        user.value = userInfo
        
        // 存储到localStorage
        setToken(jwt_token)
        setUserInfo(userInfo)
        
        return {
          success: true,
          message: response.message || '登录成功'
        }
      } else {
        return {
          success: false,
          message: response.message || '登录失败，请检查用户名或密码'
        }
      }
    } catch (error: any) {
      console.error('登录接口请求错误:', error)
      let errorMessage = '登录请求失败'
      
      if (error.response) {
        if (error.response.data && error.response.data.message) {
          errorMessage = error.response.data.message
        } else if (error.response.status === 401) {
          errorMessage = '用户名或密码错误'
        } else if (error.response.status >= 500) {
          errorMessage = '服务器错误，请稍后重试'
        }
      } else if (error.request) {
        errorMessage = '网络连接失败，请检查网络'
      } else if (error.message) {
        errorMessage = error.message
      }
      
      return {
        success: false,
        message: errorMessage
      }
    } finally {
      loading.value = false
    }
  }

  // 登出方法
  const logout = async () => {
    try {
      loading.value = true
      
      // 调用登出API
      await authApi.logout()
      
      // 清除状态
      token.value = null
      user.value = null
      
      // 清除本地存储
      clearAuth()
      
      return {
        success: true,
        message: '退出登录成功'
      }
    } catch (error) {
      console.error('登出错误:', error)
      
      // 即使API调用失败，也清除本地状态
      token.value = null
      user.value = null
      clearAuth()
      
      return {
        success: false,
        message: '退出登录失败'
      }
    } finally {
      loading.value = false
    }
  }

  // 初始化认证状态
  const initAuth = () => {
    const savedToken = getToken()
    const savedUser = getUserInfo()
    
    if (savedToken && savedUser && checkIsLoggedIn()) {
      token.value = savedToken
      user.value = savedUser
    } else {
      // 如果本地数据不完整或无效，清除所有认证信息
      clearAuthState()
    }
  }

  // 清除认证状态
  const clearAuthState = () => {
    token.value = null
    user.value = null
    clearAuth()
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    if (user.value) {
      user.value = { ...user.value, ...newUserInfo }
      setUserInfo(user.value)
    }
  }

  // 检查权限
  const hasRole = (requiredRole: number) => {
    return role.value >= requiredRole
  }

  const hasPermission = (permission: string) => {
    // 这里可以根据实际需求实现权限检查逻辑
    // 目前简单返回是否已登录
    return isLoggedIn.value
  }

  // 获取用户角色名称
  const getRoleName = computed(() => {
    switch (role.value) {
      case 1:
        return '普通用户'
      case 2:
        return '编辑'
      case 3:
        return '管理员'
      case 4:
        return '超级管理员'
      default:
        return '未知'
    }
  })

  // 初始化
  initAuth()

  return {
    // 状态
    token: readonly(token),
    user: readonly(user),
    loading: readonly(loading),
    
    // 计算属性
    isLoggedIn,
    username,
    nickname,
    role,
    getRoleName,
    
    // 方法
    login,
    logout,
    initAuth,
    clearAuthState,
    updateUserInfo,
    hasRole,
    hasPermission
  }
})

// 简化导入
export default useAuthStore
